package org.ss.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;

public class WsSessionConfig extends Configurator implements ApplicationContextAware {

    private static volatile BeanFactory context;

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        if(null != httpSession){
            sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
            sec.getUserProperties().put("clientIp",httpSession.getAttribute("remoteHost"));
        }
        super.modifyHandshake(sec,request,response);
    }

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        WsSessionConfig.context = applicationContext;
    }
}
